package itdep.ui.components.address;

import ga.tapestry.internal.SelectModelBuilder;
import itdep.domain.address.Country;
import itdep.domain.address.Region;
import itdep.services.address.CountryService;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Select;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.annotations.Inject;

import java.util.List;
import java.util.Set;

/**
 * @author Ivan Khalopik
 * @version $Revision: 47 $ $Date: 2010-07-05 09:28:44 +0000 (Mon, 05 Jul 2010) $
 */
public class RegionSelect {

	@Property
	@Parameter(required = true)
	private Region value;

	@Property
	@Parameter
	private boolean editable;

	@Inject
	private CountryService countryService;

	@Inject
	private SelectModelBuilder selectModelBuilder;

	@Component
	private Zone selectRegionZone;

	@Component(
			parameters = {
					"value=country",
					"model=countryModel",
					"zone=selectRegionZone"})
	private Select countrySelect;

	@Component(
			parameters = {
					"value=value",
					"model=regionModel"})
	private Select regionSelect;

	@Property
	private Country country;

	private SelectModel countryModel;
	private SelectModel regionModel;

	public SelectModel getCountryModel() {
		if (countryModel == null) {
			final List<Country> countries = countryService.getEntities();
			countryModel = selectModelBuilder.buildFormatted(Country.class, countries, "%s", Country.NAME_PROPERTY);
		}
		return countryModel;
	}

	public SelectModel getRegionModel() {
		if (regionModel == null) {
			if (country != null) {
				final Set<Region> regions = country.getRegions();
				regionModel = selectModelBuilder.buildFormatted(Region.class, regions, "%s", Region.NAME_PROPERTY);
			} else {
				regionModel = selectModelBuilder.buildEmpty();
			}
		}
		return regionModel;
	}

	void setupRender() {
		country = value != null ? value.getCountry() : null;
	}

	Object onValueChangedFromCountrySelect(Country countryValue) {
		value = null;
		country = countryValue;
		regionModel = null;
		return selectRegionZone.getBody();
	}
}
